package com.leo.foodmaster.admin.foodMaterial.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.foodmaster.admin.foodMaterial.entity.FoodMaterial;
import com.leo.foodmaster.admin.foodMaterial.entity.FoodMaterialType;
import com.leo.foodmaster.admin.foodMaterial.mapper.FoodMaterialMapper;
import com.leo.foodmaster.admin.foodMaterial.mapper.FoodMaterialTypeMapper;
import com.leo.foodmaster.admin.foodMaterial.service.IFoodMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.util.WebUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Leo
 * @since 2021-07-14
 */
@Service
@AllArgsConstructor
public class FoodMaterialServiceImpl extends ServiceImpl<FoodMaterialMapper, FoodMaterial> implements IFoodMaterialService {
    private final FoodMaterialTypeMapper foodMaterialTypeMapper;

    /**
     * 条件分页查询食材列表
     * @param page 分页参数
     * @param processPhase 食材加工阶段
     * @param name 食材名称
     * @param brand 食材品牌
     * @param typeId 食材类型Id
     * @return IPage<FoodMaterial>
     */
    @Override
    public IPage<FoodMaterial> getFoodMaterialPageList(Page<FoodMaterial> page, String processPhase,
                                                       String name, String brand, Long typeId) {
        // 根据登录用户的公司Id查询列表
        Long organId = WebUtils.getUser().getOrganId();
        LambdaQueryWrapper<FoodMaterial> qw = Wrappers.lambdaQuery(FoodMaterial.class)
                .eq(FoodMaterial::getOrganId, organId)
                .eq(StrUtil.isNotBlank(processPhase), FoodMaterial::getProcessPhase, processPhase)
                .like(StrUtil.isNotBlank(name), FoodMaterial::getName, name)
                .like(StrUtil.isNotBlank(brand), FoodMaterial::getBrand, brand)
                .eq(BeanUtil.isNotEmpty(typeId), FoodMaterial::getTypeId, typeId)
                .orderByDesc(FoodMaterial::getCreateTime);
        return page(page, qw);
    }

    /**
     * 删除食材
     * @param foodMaterialIds 食材Ids
     * @return Result<Object>
     */
    @Override
    public Result<Object> deleteFoodMaterial(String foodMaterialIds) {
        String[] idArray = foodMaterialIds.split(StrUtil.COMMA);
        List<Long> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Long.parseLong(id));
        }
        removeByIds(idList);
        return Result.success();
    }

    /**
     * 导入食材数据
     * @param foodMaterialList 食材列表
     * @param updateSupport 更新
     * @param userName 操作者
     * @return String
     */
    @Override
    public Result<Object> importFoodMaterial(List<FoodMaterial> foodMaterialList, boolean updateSupport, String userName) {
        Long organId = WebUtils.getUser().getOrganId();
        if (foodMaterialList.isEmpty()) {
            return Result.fail("导入食材数据不能为空");
        }

        List<FoodMaterial> insertList = new ArrayList<>();
        List<FoodMaterial> updateList = new ArrayList<>();
        List<String> failureMsgList = new ArrayList<>();
        for (int i = 0; i < foodMaterialList.size(); i++) {
            foodMaterialList.get(i).setOrganId(organId);
            // 根据数据库是否已存在该食材（食材名称、食材类型相同 为已存在），将导入的食材分为新增列表和更新列表
            List<FoodMaterial> list = list(Wrappers.lambdaQuery(FoodMaterial.class)
                    .eq(FoodMaterial::getOrganId, organId)
                    .eq(FoodMaterial::getName, foodMaterialList.get(i).getName())
                    .eq(FoodMaterial::getTypeName, foodMaterialList.get(i).getTypeName()));
            // 数据库对应的食材为空，加入新增列表
            List<FoodMaterialType> foodMaterialTypes = foodMaterialTypeMapper.selectList(Wrappers.lambdaQuery(FoodMaterialType.class)
                    .eq(FoodMaterialType::getOrganId, organId)
                    .eq(FoodMaterialType::getName, foodMaterialList.get(i).getTypeName()));
            if (list.isEmpty()) {
                if (foodMaterialTypes.isEmpty()) {
                    failureMsgList.add("第【" + (i + 2) + "】行数据对应的食材类型【" + foodMaterialList.get(i).getTypeName() + "】不存在，请检查！");
                }else {
                    foodMaterialList.get(i).setTypeId(foodMaterialTypes.get(0).getId());
                    insertList.add(foodMaterialList.get(i));
                }
            }
            // 数据库对应的食材为不为空，加入更新列表
            else {
                if (foodMaterialTypes.isEmpty()) {
                    failureMsgList.add("第【" + (i + 2) + "】行数据对应的食材类型【" + foodMaterialList.get(i).getTypeName() + "】不存在，请检查！");
                }else {
                    foodMaterialList.get(i).setTypeId(foodMaterialTypes.get(0).getId());
                    foodMaterialList.get(i).setId(list.get(0).getId());
                    updateList.add(foodMaterialList.get(i));
                }
                if (!updateSupport) {
                    failureMsgList.add("第【" + (i + 2) + "】行数据对应的食材【" + foodMaterialList.get(i).getName() + "】已存在，请检查！");
                }
            }

        }

        // 如果支持更新，将已存在的食材信息更新，将新增的插入
        if (updateSupport) {
            // 插入
            saveBatch(insertList);
            // 更新
            updateBatchById(updateList);
        }
        // 不支持更新，则只新增不存在的食材信息，将已存在的食材信息作为消息返回
        else {
            // 插入
            saveBatch(insertList);
        }
        return Result.success(failureMsgList);
    }

    /**
     * 条件查询食材列表
     * @param processPhase 加工阶段
     * @param name 食材名称
     * @param brand 品牌
     * @param typeId 类型Id
     * @return List<FoodMaterial>
     */
    @Override
    public List<FoodMaterial> getFoodMaterialList(String processPhase, String name, String brand, Long typeId) {
        // 根据登录用户的公司Id查询列表
        Long organId = WebUtils.getUser().getOrganId();
        LambdaQueryWrapper<FoodMaterial> qw = Wrappers.lambdaQuery(FoodMaterial.class)
                .eq(FoodMaterial::getOrganId, organId)
                .eq(StrUtil.isNotBlank(processPhase), FoodMaterial::getProcessPhase, processPhase)
                .like(StrUtil.isNotBlank(name), FoodMaterial::getName, name)
                .like(StrUtil.isNotBlank(brand), FoodMaterial::getBrand, brand)
                .eq(BeanUtil.isNotEmpty(typeId), FoodMaterial::getTypeId, typeId);
        return list(qw);
    }
}
